<?php
defined( '_JEXEC' ) or  die('Restricted access');
jimport( 'joomla.event.plugin' );

class plgContentTweetme extends JPlugin
{
	function plgContentTweetme( &$subject, $params )
		{
			parent::__construct( $subject, $params );
			global $mainframe;
			$this->_plugin = JPluginHelper::getPlugin( 'content', 'tweetme' );
			$this->_params = new JParameter( $this->_plugin->params );
			
			$config_style = $this->_params->get( 'tweetme_button_style', 'standard.css' );
			$config_user_style = $this->_params->get( 'tweetme_css_user_template', '0' );
			if($config_user_style=='1'){
				$config_user_style = $this->_params->get( 'tweetme_css_style_user' );
				$mainframe->addCustomHeadTag('<style type="text/css">'.$config_user_style.'</style>');
			}else{
				if ($config_style == 'compact')
				{
					$mainframe->addCustomHeadTag('<link href="plugins/content/tweetme/compact.css" rel="stylesheet" type="text/css" />');
				}else{
					$mainframe->addCustomHeadTag('<link href="plugins/content/tweetme/standard.css" rel="stylesheet" type="text/css" />');
				}
			}
		}
	
	function plgContentTweetmeButton(&$article, $auto, $tweetmestyle, $tweetmewindow, $tweetmecolor, $retweetname, $urlshortener, $hashtags, $afterbefore)
	{
            	
            	  $aTweetme   = array();
                $aTweetme[] = '<div class="tweetmebutton">';
                $aTweetme[] = '<script type="text/javascript">';
				        $aTweetme[] =  "tweetmeme_url = '".$this->getArticleRoute($article)."';";
				        //$aTweetme[] =  "tweetme_url = '".$this->plgGetUrl($article)."';";
				        $aTweetme[] =  "tweetmeme_source = '".$retweetname."';";
				        $aTweetme[] =  "tweetmeme_service = '".$urlshortener."';";
                $aTweetme[] =  "tweetmeme_hashtags = '".$hashtags."';";
            	if($tweetmewindow == 'new'){
            		$aTweetme[] = "tweetme_window = 'new';";
            	}
            	if($tweetmestyle == 'compact'){
            		$aTweetme[] = "tweetmeme_style = 'compact';";
            	}else{
            		$aTweetme[] = "tweetme_bgcolor = '".$tweetmecolor."';";
            	}
            	$aTweetme[] = "tweetmeme_source = '".$retweetname."';";
            	$aTweetme[] = "tweetmeme_service = '".$urlshortener."';";
              $aTweetme[] = "tweetmeme_hashtags = '".$hashtags."';";
            	$aTweetme[] = "tweetme_title = '".$article->title."';";
            	$aTweetme[] = '</script>';
            	$aTweetme[] = '<script type="text/javascript" src="http://tweetmeme.com/i/scripts/button.js"></script>';
            	$aTweetme[] = '</div>';
            	if ($auto == 'auto')
            	{
            		if ($afterbefore == 'after'){
	            		$article->text = $article->text.implode("\n", $aTweetme);
            		}else{
	            		$article->text = implode("\n", $aTweetme).$article->text;
            		}
            	}
            	elseif ($auto == 'manual')
            	{
            		$regex = "{tweetme}";
            		$AddButtonTweetme = implode("\n", $aTweetme);
            		
            		// find all instances of plugin and put in $matches
            	    	
            	    	preg_match_all( $regex, $article->text, $matches );
            	   		
            		// Number of plugins
            		  	
            		$count = count( $matches[0] );
            		if ( $count ) {
            			$article->text = eregi_replace($regex, $AddButtonTweetme, $article->text);
            	    	}
      
		}
            	unset($aTweetme);
            	return true;
	}
	function plgContentDraw(&$row, $config_position, $tweetme, $config_user_style){
      		
    			$send = '<table width="100%" border="0"><tr valign="top">';
    			if( $config_position=='left')
    			{
    				$send .= '<td class="tweetmebutton">';
    				$send .= $tweetme.'</td><td class="space_right" style="width:100%;">';
    				echo $send; /* beginning of table */
    				$row->text = '</td></tr></table> </td></tr></table> <table width="100%"><tr><td>'.$row->text; /* building end of table */
    			}else{
    				$send .= '<td style="width:100%;">';
    				echo $send; /*  beginning of table */
    				$row->text = '</td></tr></table> </td><td style="width:100%; float: right;" class="tweetmebutton">'.$tweetme.'</td></tr> </table><table width="100%"><tr><td>'.$row->text; /* end of table */
    			}			
	}
	
	function getArticleRoute(&$obj, $encode = 'False') {
		$url = 'Error, No URL';
		if (! is_null ( $obj )) {
			//require_once (JPATH_SITE . DS . 'components' . DS . 'com_content' . DS . 'helpers' . DS . 'route.php');
			require_once (JPATH_ROOT . DS . 'components' . DS . 'com_content' . DS . 'helpers' . DS . 'route.php');
			$url = JRoute::_ ( ContentHelperRoute::getArticleRoute ($obj->slug, $obj->catslug, $obj->sectionid));
			//$url = JRoute::_ ( ContentHelperRoute::getArticleRoute ( $obj->slug, $obj->catslug, $obj->sectionid ) );
			$uri = & JURI::getInstance ();
			$base = $uri->toString ( array ('scheme', 'host', 'port' ) );
			$url = $base . $url;
			$url = JRoute::_ ( $url, true, 0 );
			if($encode == 'True'){
				return urlencode(htmlentities( $url ));
			}else {
				return  $url;
			}
		}
		return $url;
	}

	function add_ending_slash($path){
 
    	$slash_type = (strpos($path, '\\')===0) ? 'win' : 'unix'; 
 
    	$last_char = substr($path, strlen($path)-1, 1);
 
    	if ($last_char != '/' and $last_char != '\\') {
        	// no slash:
        	$path .= ($slash_type == 'win') ? '\\' : '/';
    	}
 
    	return $path;
	}
	function plgShowInIntro(&$obj, &$params, &$inintro)
	{
		if ($inintro == '1')
		{
			return true;
		}
		else
		{
			
			if (JString::strlen(strip_tags($obj->fulltext)) !='0')
			{
				if ((JRequest :: getVar('view')) == 'article')
				{
					return true;				
				}else{
					return false;
				}
			}else{
				return true;
			}
		}
	}
	function onBeforeDisplayContent(&$row, &$params)
	{	
    		if( isset($row->author) ) {
			
    			if ($this->plgContentCheckSecCatArt($row) == false)
			{
          		$plugin = & JPluginHelper::getPlugin('content', 'tweetme');
          		$pluginParams  = new JParameter( $plugin->params );
          		$pluginRegistry  = $pluginParams->_registry['_default']['data'];
          		$sAutoTweetme = $pluginRegistry->auto_manual;
          		$sConfig_User_Style = $this->_params->get( 'tweetme_css_user_template', '0' );
			$sShowInIntro = $this->_params->get( 'tweetme_show_in_intro_text', '0' );
			$sShowFrontpage = $pluginRegistry->tweetme_show_frontpage;
      			$sShowSection = $pluginRegistry->tweetme_show_section;
	      		$sShowCate = $pluginRegistry->tweetme_show_cate;
	      		if ($this->plgTweetmeShowSecCatFP($sShowFrontpage, $sShowSection, $sShowCate) == true){
			if ($this->plgShowInIntro($row, $params, $sShowInIntro) == true)
			{
              			if ($sAutoTweetme == 'title'){
          				$sTweetmeButtonStyle = $pluginRegistry->tweetme_button_style;
	          			$sTweetmeWindow = $pluginRegistry->tweetme_new_windows;
        	  			$sTweetmeColor = $pluginRegistry->tweetme_bg_color;
        	  			$sRetweetName = $pluginRegistry->retweetname;
        	  			$sUrlShortener = $pluginRegistry->urlshortener;
                  $sHashTags = $pluginRegistry->hashtags;
        	  			$sTweetmeButtonStyle = $pluginRegistry->tweetme_button_style;
        	  			$sRetweetName = $pluginRegistry->retweetname;
        	  			$sUrlShortener = $pluginRegistry->urlshortener;
                  $sHashTags = $pluginRegistry->hashtags;
        	  			$sTweetmeButtonAling = $pluginRegistry->leftright;
        	  			$tweetme_source = '<script type="text/javascript">';
        	  			$tweetme_source .= "tweetmeme_url =  '".$this->getArticleRoute($row)."';";        	  			
        	  			$tweetme_source .= "tweetme_window = '".$sTweetmeWindow."';";
        	  			$tweetme_source .= "tweetme_bgcolor = '".$sTweetmeColor."';";
        	  			$tweetme_source .= "tweetmeme_source = '".$sRetweetName."';";
        	  			$tweetme_service .= "tweetmeme_service = '".$sUrlShortener."';";
        	  			$tweetme_service .= "tweetmeme_hashtags = '".$sHashTags."';";
        	   			$tweetme_source .= "tweetme_title = '".htmlspecialchars(utf8_encode($row->title))."';"; 
        	  			if($sTweetmeButtonStyle == 'compact')
					{
        	  	            		$tweetme_source .= "tweetmeme_style = 'compact';";        	  	            		
        	              		}
        	  			$tweetme_source .= '</script>';
        	  			$tweetme_source .= '<script type="text/javascript" src="http://tweetmeme.com/i/scripts/button.js"></script>';
        	  			$this->plgContentDraw($row, $sTweetmeButtonAling, $tweetme_source, $sConfig_User_Style);
        	  		}
			}
    			}
    			}
    		}
	}
	function plgContentCheckSecCatArt(&$row)
	{
		$plugin = & JPluginHelper::getPlugin('content', 'tweetme');
		$pluginParams  = new JParameter( $plugin->params );
		$pluginRegistry  = $pluginParams->_registry['_default']['data'];
		$value_sec = 0;
		$value_cat = 0;
		$value_art = 0;
		if ($pluginRegistry->sectionid !=''){
	
			// Check accepted section	
  			$aAcceptedSectionsArray = array();
  			$aAcceptedSectionsArray = explode(',',$pluginRegistry->sectionid);
  			if(in_array($row->sectionid, $aAcceptedSectionsArray) != true){
   				$value_sec = '1';
  			}
  			unset($aAcceptedSectionsArray);
  		}
	  	
  			// Check accepted category
  		if ($pluginRegistry->catid !=''){
  			$aAcceptedCategoryArray = array();
  			$aAcceptedCategoryArray = explode(',',$pluginRegistry->catid);
  			if(in_array($row->catid, $aAcceptedCategoryArray) != true){
    				$value_cat = '1';
  			}
			unset($aAcceptedCategoryArray);
  		}
  			
  			
  			// Check ignored articles
  		if ($pluginRegistry->articleid !=''){
	  		$aIgnoredArticleArray = array();
  			$aIgnoredArticleArray = explode(',',$pluginRegistry->articleid);
  			if(in_array($row->id, $aIgnoredArticleArray) ){
				$value_art = '1';
	  		}
	  		unset($aIgnoredArticleArray);
  		}
  		if( ($value_sec==1) || ($value_cat==1) || ($value_art==1) ){
  			return true;
  		}else{
  			return false;
  		}
  		
  	}
  	function plgTweetmeShowSecCatFP($fron_page, $sec, $cat)
	{
		$view_ddrfs = JRequest :: getVar('view');
		// echo $view_ddrfs;
		switch ($view_ddrfs)
		{
			case 'article':
				return true;
				break;
			case 'frontpage':
				if ($fron_page == '1')
				{
					return true;
				}else{
					return false;
				}
				break;
			case 'section':
				if ($sec == '1')
				{
					return true;
				}else{
					return false;
				}
				break;
			case 'category':
				if ($cat == '1')
				{
					return true;
				}else{
					return false;
				}
				break;
		}
	}
	function onPrepareContent( &$article, &$params, $limitstart )
	{
		    	$plugin = & JPluginHelper::getPlugin('content', 'tweetme');
			$pluginParams  = new JParameter( $plugin->params );
			$pluginRegistry  = $pluginParams->_registry['_default']['data'];
			
			$sTweetmeButtonStyle = $pluginRegistry->tweetme_button_style;
			$sTweetmeWindow = $pluginRegistry->tweetme_new_windows;
			$sTweetmeColor = $pluginRegistry->tweetme_bg_color;
			$sRetweetName = $pluginRegistry->retweetname;
			$sUrlShortener = $pluginRegistry->urlshortener;
      $sHashTags = $pluginRegistry->hashtags;
			$sAutoTweetme = $pluginRegistry->auto_manual;
			$sAfterBefore = $pluginRegistry->tweetme_after_before;
			if ($sAutoTweetme == 'title'){
				if ( $pluginParams->get( 'enabled', 1 ) ) {
					$regex = "#{tweetme}#";
					$article->text = preg_replace( $regex, '', $article->text);
				}
				return true;
			}elseif ($sAutoTweetme == 'auto'){
				
				if ($this->plgContentCheckSecCatArt($article) == true){
					return true;
				}
				if ( $pluginParams->get( 'enabled', 1 ) ) {
					$regex = "#{tweetme}#";
					$article->text = preg_replace( $regex, '', $article->text);
		    		}		
			}
			
			// Add Tweetme Button
		        $sShowInIntro = $this->_params->get( 'tweetme_show_in_intro_text', '0' );
		        $sShowFrontpage = $pluginRegistry->tweetme_show_frontpage;
      			$sShowSection = $pluginRegistry->tweetme_show_section;
	      		$sShowCate = $pluginRegistry->tweetme_show_cate;
		        if ($this->plgTweetmeShowSecCatFP($sShowFrontpage, $sShowSection, $sShowCate) == true){
			if ($this->plgShowInIntro($article, $params, $sShowInIntro) == true){
		        	$this->plgContentTweetmeButton($article, $sAutoTweetme, $sTweetmeButtonStyle, $sTweetmeWindow, $sTweetmeColor, $sRetweetName, $sUrlShortener, $sHashTags, $sAfterBefore);
		        }
		        }
	}
}
?>
